<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/8/23
 * Time: 11:14
 */
namespace app\common\service;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * Class ExcelService 表格导出
 */
class ExcelService
{

    public static function spreadSheet($expTableData=array(),$expCellName=array(),$expTitle='')
    {

        if(empty($expCellName)) {
            return false;
        }
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $spreadsheet = new Spreadsheet();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $spreadsheet->setActiveSheetIndex(0);
        $sheet = $spreadsheet->getActiveSheet();
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        for($i=0;$i<$cellNum;$i++){
            $sheet->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
        }
        // 自动调节大小
        foreach ($expCellName AS $k => $v) {
            $sheet->getColumnDimension($cellName[$k])->setWidth(18);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $sheet->setCellValue($cellName[$j].($i+2), ' '.$expTableData[$i][$expCellName[$j][0]]);
            }
        }
        $filename = $xlsTitle.'.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件

//        header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header("Content-Disposition: attachment;filename={$filename}");//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        return true;
    }

}